<?php

class Jf {

    /**
     * 日志操作
     * 
     * @param string $message 消息文本
     * @param number $priority 消息级别 <pre>分类：
     *        EMERG = 0, Emergency: 系统不可用
     *        ALERT = 1, Alert: 报警
     *        CRIT = 2, Critical: 紧要
     *        ERR = 3, Error: 错误
     *        WARN = 4, Warning: 警告
     *        NOTICE = 5, Notice: 通知
     *        INFO = 6, Informational: 一般信息
     *        DEBUG = 7, Debug: 调试信息
     * @param string $file 日志文件名称
     */
    public static function log($message, $priority = 6, $file = '') {
        $dispatcher = Jf_Controller_Dispatcher::getInstance();
        $request = $dispatcher->getRequest();
        $priority = is_null($priority) ? Zend_Log::INFO : $priority;
        $file = empty($file) ? 'system.log' : $file;
        $logDir = VAR_PATH . DIRECTORY_SEPARATOR . 'log';
        $logFile = $logDir . DIRECTORY_SEPARATOR . $file;
        if (! is_dir($logDir)) {
            self::mkdir($logDir);
        }
        $writer = new Zend_Log_Writer_Stream($logFile);
        $format = '%timestamp% %priorityName% (%priority%): %message% - [%modules%-%controller%-%action%] - %ip_address%' . PHP_EOL;
        $formatter = new Zend_Log_Formatter_Simple($format);
        $writer->setFormatter($formatter);
        $logger = new Zend_Log($writer);
        $logger->setEventItem('modules', $request->getModuleName());
        $logger->setEventItem('controller', $request->getControllerName());
        $logger->setEventItem('action', $request->getActionName());
        $logger->setEventItem('ip_address', $_SERVER['REMOTE_ADDR']);
        $logger->log($message, $priority);
    }

    public static function mkdir($path, $chmod = 0777) {
        return is_dir($path) or (self::mkdir(dirname($path), $chmod) and mkdir($path, $chmod));
    }

    public static function normalizePropertyName($property) {
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $property)));
    }

    public static function loadModel($model, $arguments = array()) {
        $class = self::getClass($model, $type = 'Model');
        return self::loadByRegistry($class, $arguments);
    }

    public static function getModel($model, $arguments = array()) {
        $class = self::getClass($model, $type = 'Model');
        return self::loadByRegistry($class, $arguments);
    }

    public static function getResource($model, $arguments = array()) {
        $class = self::getClass($model, $type = 'Model_Resource');
        return self::loadByRegistry($class, $arguments);
    }

    public static function loadValidate($validate, $arguments = array()) {
        $class = self::getClass($validate, $type = 'Validate');
        return self::load($class, $arguments);
    }

    public function getPlugin($plugin, $arguments = array()) {
        $class = self::getClass($plugin, $type = 'Plugin');
        return self::load($class, $arguments);
    }

    public function getService($service, $arguments = array()) {
        $class = self::getClass($service, $type = 'Service');
        return self::load($class, $arguments);
    }

    public static function loadByRegistry($class, $arguments = array()) {
        if (! Jf_Registry::isRegistered($class)) {
            $instance = new $class($arguments);
            Jf_Registry::set($class, $instance);
        }
        return Jf_Registry::get($class);
    }

    public static function load($class, $arguments = array()) {
        return $instance = new $class($arguments);
    }

    public static function getClass($name, $type) {
        $parts = explode('/', $name);
        if (count($parts) > 1) {
            $nameSpace = ucfirst(array_shift($parts));
        } else {
            $moduleName = Jf_Controller_Dispatcher::getInstance()->getRequest()->getModuleName();
            $nameSpace = ucfirst($moduleName);
        }
        $name = '';
        foreach ((array) $parts as $value) {
            $name .= '_';
            $name .= ucwords($value);
        }
        return $nameSpace . '_' . ucfirst($type) . $name;
    }

    /**
     * 缓存设置
     * 
     * @param string $type 类型[redis/memcached/ssdb]
     * @return mixed
     */
    public static function cache($type = 'redis') {
        switch ($type) {
            case 'redis':
                if (! Jf_Registry::isRegistered('redis')) {
                    if (! class_exists('Redis')) {
                        require_once (PUB_PATH . DIRECTORY_SEPARATOR . 'Redis.php');
                    }
                    $redis = new Redis();
                    $redis->connect('127.0.0.1', '6379');
                    $redis->auth('foobared');
                    Jf_Registry::set('redis', $redis);
                }
                break;
            case 'memcached':
                if (! Jf_Registry::isRegistered('memcached')) {
                    if (! class_exists('Memcached')) {
                        require_once (PUB_PATH . DIRECTORY_SEPARATOR . 'Memcached.php');
                    }
                    $class = 'Memcached';
                    $memcached = new $class();
                    $memcached->addServer('127.0.0.1', '11211');
                    Jf_Registry::set('memcached', $memcached);
                }
                break;
            default:
                if (! Jf_Registry::isRegistered($type)) {
                    $ssdb = new Jf_SSDB('127.0.0.1', '11210');
                    Jf_Registry::set($type, $ssdb);
                }
                break;
        }
        return Jf_Registry::get($type);
    }

    public static function getUniqueCode($length = null) {
        $code = md5(uniqid(rand(), true));
        if (isset($length))
            return substr($code, 0, $length);
        else
            return $code;
    }

    public static function getHelper($helper, $args = array()) {
        $helperClass = self::getClass($helper, $type = 'helper');
        $helperArr = explode('/', $helper);
        $helper = array_pop($helperArr);
        return call_user_func_array(array(
            new $helperClass(),
            $helper
        ), (array) $args);
    }
}
